﻿#region Disclaimer/License Info

/* *********************************************** */

// sBlog.Net

// sBlog.Net is a minimalistic blog engine software.

// Homepage: http://sblogproject.net
// Github: http://github.com/karthik25/sBlog.Net

// This project is licensed under the BSD license.  
// See the License.txt file for more information.

/* *********************************************** */

#endregion
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using sBlog.Net.Common;
using sBlog.Net.DependencyManagement;
using sBlog.Net.Domain.Entities;
using sBlog.Net.Domain.Interfaces;
using sBlog.Net.FluentExtensions;

namespace sBlog.Net.Controllers
{
    public class HomeController : Controller
    {
        private readonly IPost _postRepository;
        private readonly ISettings SettingsRepository;
        private readonly IUser _userRepository;

        public HomeController()
        {
            _postRepository = InstanceFactory.CreatePostInstance();
            SettingsRepository = InstanceFactory.CreateSettingsInstance();
            _userRepository = InstanceFactory.CreateUserInstance();
        }

        protected int GetUserId()
        {
            var userId = -1;
            if (Request.IsAuthenticated)
            {
                var userIdentity = (IUserInfo)User.Identity;
                userId = Int32.Parse(userIdentity.UserId);
            }
            return userId;
        }

        protected string GetRootUrl()
        {
            return string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
        }

        //
        // GET: /page/[pageNumber]
        [Authorize]
        public ActionResult Index(int? pageNumber)
        {
            List<PostEntity> postEntities = MemcaheService.GetHomePageWithPage(10, Convert.ToInt32(1));
            var blogPostModel = postEntities.GetBlogPostPageViewModel(pageNumber, SettingsRepository, _postRepository, GetRootUrl());
            return View(blogPostModel);
        }

        public JsonResult LoadMoreData(int pageNumber)
        {
            List<PostEntity> postEntities = MemcaheService.GetHomePageWithPage(10, pageNumber);
            var blogPostModel = postEntities.GetBlogPostPageViewModel(1, SettingsRepository, _postRepository, GetRootUrl());

            var stringHtml = RenderPartialViewToString("RenderPostItem", blogPostModel);
            return Json(stringHtml, JsonRequestBehavior.AllowGet);
        }

        public JsonResult loadMostViewByCat(string catslug)
        {
            var model = MemcaheService.GetMostViewPostByCatSlug(catslug);
            var stringHtml = RenderPartialViewToString("PostMostViewByCat", model);
            return Json(stringHtml, JsonRequestBehavior.AllowGet);
        }

        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

        [Authorize]
        public ActionResult PostsByTag(string tagName, int? pageNumber)
        {
            List<PostEntity> postEntities = MemcaheService.GetPostsByTagWithPage(tagName, 10, Convert.ToInt32(1));
            var blogPostModel = postEntities.GetBlogPostPageViewModel(pageNumber, SettingsRepository, _postRepository, GetRootUrl());
            blogPostModel.Tag = GetTagEntity(tagName);

            CategoryEntity catEntity = new CategoryEntity();
            catEntity.CategorySlug = "All";
            ViewData["catEntity"] = catEntity;

            return View(blogPostModel);
        }

        public JsonResult LoadMorePostsByTag(string tagName, int pageNumber)
        {
            List<PostEntity> postEntities = MemcaheService.GetPostsByTagWithPage(tagName, 10, Convert.ToInt32(pageNumber));
            var blogPostModel = postEntities.GetBlogPostPageViewModel(1, SettingsRepository, _postRepository, GetRootUrl());
            blogPostModel.Tag = GetTagEntity(tagName);

            CategoryEntity catEntity = new CategoryEntity();
            catEntity.CategorySlug = "All";
            ViewData["catEntity"] = catEntity;

            var stringHtml = RenderPartialViewToString("RenderPostItem", blogPostModel);
            return Json(stringHtml, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /category/categoryName
        [Authorize]
        public ActionResult PostsByCategory(string categoryName, int? pageNumber)
        {
            if (GetUserId() == -1)
            {
                List<PostEntity> postEntities = MemcaheService.GetPostsByCategoryWithPage(categoryName, 10, 1);
                var blogPostModel = postEntities.GetBlogPostPageViewModel(pageNumber, SettingsRepository, _postRepository, GetRootUrl());

                blogPostModel.Category = GetCategoryEntity(categoryName);
                //Get Post by cat for SileBar
                CategoryEntity catEntity = new CategoryEntity();
                switch (categoryName)
                {
                    case "hinh-anh":
                        catEntity.CategorySlug = "hinh-anh";
                        break;
                    case "bai-viet":
                        catEntity.CategorySlug = "bai-viet";
                        break;
                    case "video":
                        catEntity.CategorySlug = "video";
                        break;
                    default:
                        catEntity.CategorySlug = "All";
                        break;
                }

                ViewData["catEntity"] = catEntity;
                //End
                return View(blogPostModel);
            }
            else
            {
                List<PostEntity> postEntities = MemcaheService.GetPostsByCategoryWithPage(categoryName, 10, 1);
                //Get Post By FollowingUserId
                List<PostEntity> followingAuthorPosts = null;
                List<FollowEntity> lstFollow = MemcaheService.GetFollowByFollowingUserID(GetUserId());
                if (lstFollow.Count > 0)
                {

                    foreach (FollowEntity follow in lstFollow)
                    {
                        followingAuthorPosts = MemcaheService.GetMostViewPostByCatSlugAndOwnerUserID(follow.FollowerUserID, categoryName);
                        postEntities.AddRange(followingAuthorPosts);
                    }
                }

                postEntities = postEntities.OrderByDescending(x => x.PublicDate).ToList();

                var blogPostModel = postEntities.GetBlogPostPageViewModel(pageNumber, SettingsRepository, _postRepository, GetRootUrl());
                blogPostModel.Category = GetCategoryEntity(categoryName);

                //Get Post by cat for SileBar
                CategoryEntity catEntity = new CategoryEntity();
                switch (categoryName)
                {
                    case "hinh-anh":
                        catEntity.CategorySlug = "hinh-anh";
                        break;
                    case "bai-viet":
                        catEntity.CategorySlug = "bai-viet";
                        break;
                    case "video":
                        catEntity.CategorySlug = "video";
                        break;
                    default:
                        catEntity.CategorySlug = "All";
                        break;
                }

                ViewData["catEntity"] = catEntity;
                //End
                return View(blogPostModel);
            }
        }

        public JsonResult LoadMoreDataCat(string categoryName, int pageNumber)
        {
            if (GetUserId() == -1)
            {
                List<PostEntity> postEntities = MemcaheService.GetPostsByCategoryWithPage(categoryName, 10, pageNumber);
                var blogPostModel = postEntities.GetBlogPostPageViewModel(1, SettingsRepository, _postRepository, GetRootUrl());
                blogPostModel.Category = GetCategoryEntity(categoryName);
                //Get Post by cat for SileBar
                CategoryEntity catEntity = new CategoryEntity();
                switch (categoryName)
                {
                    case "hinh-anh":
                        catEntity.CategorySlug = "hinh-anh";
                        break;
                    case "bai-viet":
                        catEntity.CategorySlug = "bai-viet";
                        break;
                    case "video":
                        catEntity.CategorySlug = "video";
                        break;
                    default:
                        catEntity.CategorySlug = "All";
                        break;
                }

                ViewData["catEntity"] = catEntity;
                //End
                var stringHtml = RenderPartialViewToString("RenderPostItem", blogPostModel);
                return Json(stringHtml, JsonRequestBehavior.AllowGet);

            }
            else
            {
                List<PostEntity> postEntities = MemcaheService.GetPostsByCategoryWithPage(categoryName, 10, pageNumber);
                //Get Post By FollowingUserId
                List<PostEntity> followingAuthorPosts = null;
                List<FollowEntity> lstFollow = MemcaheService.GetFollowByFollowingUserID(GetUserId());
                if (lstFollow.Count > 0)
                {
                    foreach (FollowEntity follow in lstFollow)
                    {
                        followingAuthorPosts = MemcaheService.GetMostViewPostByCatSlugAndOwnerUserID(follow.FollowerUserID, categoryName);
                        postEntities.AddRange(followingAuthorPosts);
                    }
                }

                var blogPostModel = postEntities.GetBlogPostPageViewModel(1, SettingsRepository, _postRepository, GetRootUrl());
                blogPostModel.Category = GetCategoryEntity(categoryName);

                //Get Post by cat for SileBar
                CategoryEntity catEntity = new CategoryEntity();
                switch (categoryName)
                {
                    case "hinh-anh":
                        catEntity.CategorySlug = "hinh-anh";
                        break;
                    case "bai-viet":
                        catEntity.CategorySlug = "bai-viet";
                        break;
                    case "video":
                        catEntity.CategorySlug = "video";
                        break;
                    default:
                        catEntity.CategorySlug = "All";
                        break;
                }

                ViewData["catEntity"] = catEntity;
                //End                
                var stringHtml = RenderPartialViewToString("RenderPostItem", blogPostModel);
                return Json(stringHtml, JsonRequestBehavior.AllowGet);
            }
        }

        //
        //Home/SearchPost
        [Authorize]
        public ActionResult SearchPost(string textSearch, int? pageNumber)
        {
            List<PostEntity> postEntities = MemcaheService.SearchKeywordWithPage(textSearch, 1, 10);
            var blogPostModel = postEntities.GetBlogPostPageViewModel(pageNumber, SettingsRepository, _postRepository, GetRootUrl());

            return View(blogPostModel);
        }

        public JsonResult LoadMoreSearch(string textSearch, int pageNumber)
        {
            List<PostEntity> postEntities = MemcaheService.SearchKeywordWithPage(textSearch, Convert.ToInt32(pageNumber), 10);
            var blogPostModel = postEntities.GetBlogPostPageViewModel(1, SettingsRepository, _postRepository, GetRootUrl());
            var stringHtml = RenderPartialViewToString("RenderPostItem", blogPostModel);
            return Json(stringHtml, JsonRequestBehavior.AllowGet);
        }

        public JsonResult loadInfoAuthorBy(string type, int OwnerUserID)
        {
            var stringHtml = string.Empty;
            if (type.Equals("tong-quat"))
            {
                UserEntity userOwner = _userRepository.GetUserObjByUserID(OwnerUserID);
                stringHtml = RenderPartialViewToString("AuthorTongQuat", userOwner);
            }
            else if (type.Equals("bai-viet-moi"))
            {
                var post = _postRepository.GetNewPostByAuthor(OwnerUserID);
                stringHtml = RenderPartialViewToString("AuthorNewPost", post);
            }
            return Json(stringHtml, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Error()
        {
            return RedirectToAction("Index", "Home");
            //var errType = Request.QueryString["err"];

            //var blogErrorViewModel = new BlogErrorViewModel
            //{
            //    Title = SettingsRepository.BlogName,
            //    ErrorCode = errType,
            //    ErrorDescription = "An unknown error has occurred"
            //};
            //if (!string.IsNullOrEmpty(errType))
            //{
            //    switch (errType)
            //    {
            //        case "unauthorized":
            //            blogErrorViewModel.ErrorDescription = "An unauthorized access was detected";
            //            break;
            //        case "invalid-month":
            //            blogErrorViewModel.ErrorDescription = "Month/year in the url is invalid";
            //            break;
            //        default:
            //            blogErrorViewModel.ErrorDescription = "An unknown error has occurred";
            //            break;
            //    }
            //}
            //return View("Error", blogErrorViewModel);
        }

        private TagEntity GetTagEntity(string tagName)
        {
            var tagEntity = MemcaheService.GetTagEntityByTagSlug(tagName).FirstOrDefault() ??
                            new TagEntity { TagName = tagName };
            return tagEntity;
        }

        private CategoryEntity GetCategoryEntity(string categoryName)
        {
            var categoryEntity = MemcaheService.GetCategoryEntityByCategorySlug(categoryName).FirstOrDefault() ??
                                 new CategoryEntity { CategoryName = categoryName };
            return categoryEntity;
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        public byte[] imageToByteArrayForContent(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            ImageFormat imageFormat = imageIn.RawFormat;
            imageIn.Save(ms, imageFormat);
            return ms.ToArray();
        }

        //public string UploadAvatar(HttpPostedFileBase fileData)
        //{
        //    Byte[] buffer = new Byte[1];

        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        //    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        //    string ftpUploadUrl = string.Empty;
        //    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

        //    string imgUrl = string.Empty;
        //    string strName = string.Empty;
        //    string folderName = string.Empty;
        //    try
        //    {
        //        if (Common.Global.EditStatus == false)
        //        {
        //            folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
        //        }
        //        else
        //        {
        //            folderName = Common.Global.ImgFolder;
        //        }

        //        imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;

        //        //Create Folder
        //        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        //        strFtpAddress = strFtpAddress + folderName;

        //        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        //        ////////
        //        Bitmap bmp = new Bitmap(fileData.InputStream);
        //        buffer = ImageUtility.SaveImage(bmp, 100L);
        //        ftpUploadUrl = strFtpAddress + "/" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp80 = new Bitmap(fileData.InputStream);
        //        if (bmp80.Width > 80 || bmp80.Height > 80)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp80, new Rectangle(0, 0, 80, 80));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp80.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp80, 100L);
        //        ftpUploadUrl = strFtpAddress + "/80x80_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp80.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp110 = new Bitmap(fileData.InputStream);
        //        if (bmp110.Width > 110 || bmp110.Height > 120)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp110, new Rectangle(0, 0, 110, 120));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp110.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp110, 100L);
        //        ftpUploadUrl = strFtpAddress + "/110x120_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp110.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp70 = new Bitmap(fileData.InputStream);
        //        if (bmp70.Width > 70 || bmp70.Height > 40)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp70, new Rectangle(0, 0, 70, 44));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp70.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp70, 100L);
        //        ftpUploadUrl = strFtpAddress + "/70x44_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp70.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp196 = new Bitmap(fileData.InputStream);
        //        if (bmp196.Width > 196 || bmp196.Height > 196)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp196, new Rectangle(0, 0, 196, 196));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp196.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp196, 100L);
        //        ftpUploadUrl = strFtpAddress + "/196x196_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp196.Dispose();
        //        ////////
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //    imgUrl = imgUrl + "/80x80_" + strName;

        //    return imgUrl;
        //}

        //public string UploadAvatarFeature(HttpPostedFileBase fileData)
        //{
        //    Byte[] buffer = new Byte[1];

        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        //    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        //    string ftpUploadUrl = string.Empty;
        //    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

        //    string strName = string.Empty;
        //    string imgUrl = string.Empty;
        //    string folderName = string.Empty;

        //    try
        //    {
        //        if (Common.Global.EditStatus == false)
        //        {
        //            folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
        //        }
        //        else
        //        {
        //            folderName = Common.Global.ImgFolder;
        //        }

        //        imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;
        //        //Create Folder
        //        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        //        strFtpAddress = strFtpAddress + folderName;

        //        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        //        ////////
        //        Bitmap bmp990 = new Bitmap(fileData.InputStream);
        //        if (bmp990.Width > 990 || bmp990.Height > 392)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp990, new Rectangle(0, 0, 990, 392));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp990.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp990, 100L);
        //        ftpUploadUrl = strFtpAddress + "/990x392_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp990.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp80 = new Bitmap(fileData.InputStream);
        //        if (bmp80.Width > 80 || bmp80.Height > 80)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp80, new Rectangle(0, 0, 80, 80));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp80.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp80, 100L);
        //        ftpUploadUrl = strFtpAddress + "/80x80_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp80.Dispose();
        //        ////////
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //    imgUrl = imgUrl + "/80x80_" + strName;
        //    return imgUrl;
        //}

        //public string UploadAvatarYanNews(HttpPostedFileBase fileData)
        //{
        //    Byte[] buffer = new Byte[1];

        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        //    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        //    string ftpUploadUrl = string.Empty;
        //    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

        //    string strName = string.Empty;
        //    string imgUrl = string.Empty;
        //    string folderName = string.Empty;

        //    try
        //    {
        //        if (Common.Global.EditStatus == false)
        //        {
        //            folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
        //        }
        //        else
        //        {
        //            folderName = Common.Global.ImgFolder;
        //        }

        //        imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;

        //        //Create Folder
        //        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);
        //        strFtpAddress = strFtpAddress + folderName;

        //        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        //        ////////
        //        Bitmap bmp550 = new Bitmap(fileData.InputStream);
        //        if (bmp550.Width > 550 || bmp550.Height > 275)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp550, new Rectangle(0, 0, 550, 275));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp550.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp550, 100L);
        //        ftpUploadUrl = strFtpAddress + "/550x275_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp550.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp300 = new Bitmap(fileData.InputStream);
        //        if (bmp300.Width > 300 || bmp300.Height > 150)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp300, new Rectangle(0, 0, 300, 150));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp300.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp300, 100L);
        //        ftpUploadUrl = strFtpAddress + "/300x150_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp300.Dispose();
        //        ////////
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);

        //    }

        //    imgUrl = imgUrl + "/300X150_" + strName;
        //    return imgUrl;
        //}

        //public string UploadAvatarSquare(HttpPostedFileBase fileData)
        //{
        //    Byte[] buffer = new Byte[1];

        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        //    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        //    string ftpUploadUrl = string.Empty;
        //    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

        //    string strName = string.Empty;
        //    string imgUrl = string.Empty;
        //    string folderName = string.Empty;
        //    try
        //    {
        //        if (Common.Global.EditStatus == false)
        //        {
        //            folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
        //        }
        //        else
        //        {
        //            folderName = Common.Global.ImgFolder;
        //        }

        //        imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;

        //        //Create Folder
        //        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        //        strFtpAddress = strFtpAddress + folderName;

        //        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        //        ////////
        //        Bitmap bmp196 = new Bitmap(fileData.InputStream);
        //        if (bmp196.Width > 196 || bmp196.Height > 196)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp196, new Rectangle(0, 0, 196, 196));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp196.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp196, 100L);
        //        ftpUploadUrl = strFtpAddress + "/196x196_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp196.Dispose();
        //        ////////

        //        ////////
        //        Bitmap bmp80 = new Bitmap(fileData.InputStream);
        //        if (bmp80.Width > 80 || bmp80.Height > 80)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp80, new Rectangle(0, 0, 80, 80));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp80.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp80, 100L);
        //        ftpUploadUrl = strFtpAddress + "/80x80_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp80.Dispose();
        //        ////////
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //    imgUrl = imgUrl + "/80x80_" + strName;
        //    return imgUrl;
        //}

        //public string UploadVideo(HttpPostedFileBase fileData)
        //{
        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserNameVideo"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPasswordVideo"].ToString();

        //    string strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);
        //    string strPath = Path.Combine(Server.MapPath("~/UploadVideos"), strName);
        //    fileData.SaveAs(strPath);

        //    /////////////
        //    sBlog.Net.Common.ImageUtility.UploadVideoToFTP(System.Configuration.ConfigurationManager.AppSettings["ftpServerVideo"].ToString() + "Mlog/UploadVideos/" + strName, strPath, strUserNameFtp, strPassFtp);
        //    //////////////

        //    if (Directory.Exists(Path.GetDirectoryName(strPath)))
        //    {
        //        System.IO.File.Delete(strPath);
        //    }

        //    return strName;
        //}

        ////public string UploadUserAvatar(HttpPostedFileBase fileData)
        ////{
        ////    Byte[] buffer = new Byte[1];

        ////    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        ////    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        ////    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        ////    string ftpUploadUrl = string.Empty;
        ////    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadUserAvatar/";

        ////    string strName = string.Empty;
        ////    string imgUrl = string.Empty;

        ////    try
        ////    {
        ////        string folderName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");

        ////        imgUrl = httpServer + "Mlog/UploadUserAvatar/" + folderName;
        ////        //Create Folder
        ////        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        ////        strFtpAddress = strFtpAddress + folderName;

        ////        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        ////        ////////
        ////        Bitmap bmp = new Bitmap(fileData.InputStream);
        ////        buffer = ImageUtility.SaveImage(bmp, 100L);
        ////        ftpUploadUrl = strFtpAddress + strName;
        ////        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        ////        bmp.Dispose();
        ////        ////////

        ////        ////////
        ////        Bitmap bmp30 = new Bitmap(fileData.InputStream);
        ////        if (bmp30.Width > 30 || bmp30.Height > 30)
        ////        {
        ////            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp30, new Rectangle(0, 0, 30, 30));
        ////            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        ////            bmp30.Dispose();
        ////            bmpResize.Dispose();
        ////        }
        ////        else buffer = ImageUtility.SaveImage(bmp30, 100L);
        ////        ftpUploadUrl = strFtpAddress + "/30x30_" + strName;
        ////        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        ////        bmp30.Dispose();
        ////        ////////

        ////        ////////
        ////        Bitmap bmp70 = new Bitmap(fileData.InputStream);
        ////        if (bmp70.Width > 70 || bmp70.Height > 70)
        ////        {
        ////            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp30, new Rectangle(0, 0, 70, 70));
        ////            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        ////            bmp70.Dispose();
        ////            bmpResize.Dispose();
        ////        }
        ////        else buffer = ImageUtility.SaveImage(bmp70, 100L);
        ////        ftpUploadUrl = strFtpAddress + "/70x70_" + strName;
        ////        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        ////        bmp70.Dispose();
        ////        ////////
        ////    }
        ////    catch (Exception ex)
        ////    {
        ////        throw new Exception(ex.Message);
        ////    }

        ////    imgUrl = imgUrl + "/" + strName;
        ////    return imgUrl;
        ////}

        ////public string UploadUserAvatarFace(HttpPostedFileBase fileData)
        ////{
        ////    Byte[] buffer = new Byte[1];

        ////    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        ////    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        ////    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        ////    string ftpUploadUrl = string.Empty;
        ////    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadUserAvatarFace/";

        ////    string strName = string.Empty;
        ////    string imgUrl = string.Empty;

        ////    try
        ////    {
        ////        string folderName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");
        ////        imgUrl = httpServer + "Mlog/UploadUserAvatarFace/" + folderName;
        ////        //Create Folder
        ////        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        ////        strFtpAddress = strFtpAddress + folderName;

        ////        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        ////        ////////
        ////        Bitmap bmp129 = new Bitmap(fileData.InputStream);
        ////        if (bmp129.Width > 129 || bmp129.Height > 129)
        ////        {
        ////            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp129, new Rectangle(0, 0, 129, 129));
        ////            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        ////            bmp129.Dispose();
        ////            bmpResize.Dispose();
        ////        }
        ////        else buffer = ImageUtility.SaveImage(bmp129, 100L);
        ////        ftpUploadUrl = strFtpAddress + "/129x129_" + strName;
        ////        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        ////        bmp129.Dispose();
        ////        ////////
        ////    }
        ////    catch (Exception ex)
        ////    {
        ////        throw new Exception(ex.Message);
        ////    }

        ////    imgUrl = imgUrl + "/129x129_" + strName;
        ////    return imgUrl;
        ////}

        //public string UploadImageContent(HttpPostedFileBase fileData)
        //{
        //    Byte[] buffer = new Byte[1];

        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
        //    string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

        //    string ftpUploadUrl = string.Empty;
        //    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/ImageContent/";

        //    string strName = string.Empty;
        //    string imgUrl = string.Empty;

        //    try
        //    {
        //        string folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");

        //        imgUrl = httpServer + "Mlog/ImageContent/" + folderName;

        //        //Create Folder
        //        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        //        strFtpAddress = strFtpAddress + folderName;

        //        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        //        ////////
        //        Bitmap bmp = new Bitmap(fileData.InputStream);
        //        buffer = ImageUtility.SaveImage(bmp, 100L);
        //        ftpUploadUrl = strFtpAddress + "/" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp.Dispose();
        //        ////////
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //    imgUrl = imgUrl + "/" + strName;
        //    return imgUrl;
        //}

        //public string UploadUserCover(HttpPostedFileBase fileData)
        //{
        //    Byte[] buffer = new Byte[1];

        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();

        //    string ftpUploadUrl = string.Empty;
        //    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadUserCover/";

        //    string strName = string.Empty;

        //    try
        //    {
        //        string folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
        //        //Create Folder
        //        ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

        //        strFtpAddress = strFtpAddress + folderName;

        //        strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

        //        ////////
        //        Bitmap bmp1000 = new Bitmap(fileData.InputStream);
        //        if (bmp1000.Width > 1000 || bmp1000.Height > 280)
        //        {
        //            Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp1000, new Rectangle(0, 0, 1000, 280));
        //            buffer = ImageUtility.SaveImage(bmpResize, 100L);
        //            bmp1000.Dispose();
        //            bmpResize.Dispose();
        //        }
        //        else buffer = ImageUtility.SaveImage(bmp1000, 100L);
        //        ftpUploadUrl = strFtpAddress + "/1000x280_" + strName;
        //        ImageUtility.UpFileServer(ftpUploadUrl, buffer);
        //        bmp1000.Dispose();
        //        ////////
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //    return strName;
        //}

        public JsonResult like(int postId)
        {
            int likeCount = 0;
            if (Session["like" + postId] == null)
            {
                likeCount = _postRepository.UpdateLikeCount(postId, 1);
                Session["like" + postId] = likeCount;
            }
            else
            {
                likeCount = _postRepository.GetPostByID(postId).LikeCount;
            }

            return Json(likeCount, JsonRequestBehavior.AllowGet);
        }

        public ActionResult QuyenLoi(string parameter)
        {
            return View();
        }

        public ActionResult DieuKhoanSuDung(string parameter)
        {
            return View();
        }

        public ActionResult QuangCao(string parameter)
        {
            return View();
        }

        private static readonly Random getrandom = new Random();
        private static readonly object syncLock = new object();

        public static int GetRandomNumber(int min, int max)
        {
            lock (syncLock)
            { // synchronize
                return getrandom.Next(min, max);
            }
        }

        protected override void Dispose(bool disposing)
        {
            _postRepository.Dispose();
            _userRepository.Dispose();
        }
    }
}
